<template>
  <div>
      <page-main class="searchMain">
            <div class="searchBox">
                <span>搜索</span>
                <el-input v-model="searchValue" class="search" @keyup.enter="searchInputList" placeholder="请输入ID 单位名称或者监管等级"></el-input>
            </div>
      </page-main>
    <page-main>
      <el-table
        :data="userList"
        :default-sort="{ prop: 'id', order: 'ascending' }"
      >
        <el-table-column label="id" prop="serial" sortable></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="性别" prop="sex">
          <template #default="scope">
            <span v-if="scope.row.sex == 1">男</span>
            <span v-if="scope.row.sex == 2">女</span>
            <span v-else>保密</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="区域" prop="region_name"></el-table-column>
        <el-table-column label="是否禁用">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_stop"
              active-color="#ff4949"
              inactive-color="#13ce66"
              active-text="是"
              inactive-text="否"
              :active-value="2"
              :inactive-value="1"
              @change="isStop(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"  fixed="right" >
          <template #header>
            <el-button type="primary" size="mini" @click="add">添加</el-button>
          </template>
          <template #default="scope">
            <el-button size="mini" @click="edit(scope.row, isPwdShow)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :title="title"
        v-model="dialogFormVisible"
        @close="closeForm"
        destroy-on-close
        :close-on-click-modal="false"
      >
        <el-form
          ref="childForm"
          :rules="rules"
          :model="formData"
          label-position="top"
        >
          <el-row>
            <el-col :span="6" :offset="1">
              <el-form-item label="用户名" prop="username">
                <el-input
                  style="width: 250px;"
                  v-model="formData.username"
                  oninput="value=value.replace(/[^a-zA-Z]/g,'')"
                  :maxlength="18"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1" v-if="isPwdShow">
              <el-form-item label="密 码" prop="password">
                <el-input
                  show-password
                  style="width: 250px;"
                  v-model="formData.password"
                  :maxlength="18"
                  oninput="value=value.replace(/[^a-zA-Z0-9_]/g,'')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="姓名" prop="name">
                <el-input
                  style="width: 250px;"
                  v-model="formData.name"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formData.sex">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="2">女</el-radio>
                  <!-- <el-radio label="3">保密</el-radio> -->
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="年龄" prop="age">
                <el-input
                  style="width: 250px;"
                  v-model="formData.age"
                  oninput="value=value.replace(/[^\d]/g,'')"
                  :maxlength="2"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="手机号" prop="phone">
                <el-input
                  style="width: 250px;"
                  v-model="formData.phone"
                  oninput="value=value.replace(/[^\d]/g,'')"
                  :maxlength="11"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="角色" prop="role_id">
                <el-select v-model="formData.role_id" filterable placeholder="请选择">
                  <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.role_name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="13" :offset="1">
              <el-form-item label="行政地区编号" prop="region_id">
                <span>四川省 > 攀枝花市 ></span>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="头像" prop="head_img">
                <el-upload
                  :action="upDataUrl + '/unit/upload/upload'"
                  list-type="picture-card"
                  :headers="upLoadImgHeader"
                  :data="upLoadImgData"
                  :on-success="headImgUpSuccess"
                  limit="1"
                  :file-list="fileLlist"
                  class="img"
                  :before-remove="imgRemove"
                  :on-change="imgChange"
                  accept=".jpg,.png,.jpeg"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="是否禁用" prop="is_stop">
                <el-switch
                  v-model="formData.is_stop"
                  active-color="#ff4949"
                  inactive-color="#13ce66"
                  active-text="是"
                  inactive-text="否"
                  :active-value="2"
                  :inactive-value="1"
                ></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        :current-page="pagination.page"
        :total="total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </page-main>
  </div>
</template>
<script>
import { ElMessage } from "element-plus";
// 分页
import paginationMixin from "@/mixins/pagination";
export default {
  // 分页
  mixins: [paginationMixin],
  data() {
    return {
        searchValue: '',
      // 总页数
      total: 0,
      dialogFormVisible: false,
      userList: [],
      formData: {
        id: 0, //id>0为修改，=0为添加
        region_id: "", //行政区域ID
        username: "", //用户名(6-32位)
        password: "", //密码(6-32位)
        role_id: "", //角色|ID
        name: "", //姓名
        sex: "1", //性别 1-男 2-女 3-保密
        phone: "", //电话
        head_img: "", // 头像
        age: 0, //年龄
        is_stop: "1", //是否禁用 1-否 2-是
        user_area: "xf",
      },
      rules: {
        username: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 6, max: 18, trigger: "blur", message: "用户名长度为6到18位" },
        //   {
        //     required: true,
        //     pattern: /^[a-zA-Z]+$/,
        //     message: "用户名只能是英文",
        //     trigger: "change",
        //   }, //正则
        ],
        password: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 6, max: 18, trigger: "blur", message: "密码长度为6到18位" },
        //   {
        //     required: true,
        //     pattern: /^(\w){6,20}$/,
        //     message: "密码只能是英文数字_",
        //     trigger: "change",
        //   }, //正则
        ],
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        role_id: [{ required: true, message: "请选择", trigger: "blur" }],
        sex: [{ required: true, message: "请选择", trigger: "blur" }],
        phone: [
            { required: true, message: "请输入", trigger: "blur" },
            { min: 11, max: 11, trigger: "blur", message: "请输入正确的手机号" },
            ],
        is_stop: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      fileLlist: [],
      upLoadImgData: {
        type: "image",
      },
      upDataUrl: import.meta.env.DEV
        ? "/proxy/"
        : import.meta.env.VITE_APP_API_BASEURL,
      title: "",
      // 区域数据
      // 角色列表
      roleList: [],
      upDataUrl: import.meta.env.DEV
        ? "/proxy/"
        : import.meta.env.VITE_APP_API_BASEURL,
      isPwdShow: true,
    };
  },
  computed: {
    upLoadImgHeader() {
      return {
        "A-Token": this.$store.state.user.a_token,
        "U-Token": this.$store.state.user.u_token,
      };
    },
  },
  created() {
    // 区域数据
    this.getDataList();
    this.getRoleList();
  },
  methods: {
    // 图片
    imgChange() {
      let img = document.getElementsByClassName("img")[0];
      img.children[1].style.display = "none";
    },
    imgRemove() {
      let img = document.getElementsByClassName("img")[0];
      img.children[1].style.display = "block";
    },
    // 获取用户列表 网格员area,需要添加网格, 机构员 xf 不用添加网格
    getDataList() {
      // 分页
      let query = {
        rows: this.pagination.size,
        page: this.pagination.page,
        user_area: "xf",
        keywords: this.searchValue
      };
      this.$api.post("/unit/XfUser/lists", query).then((res) => {
        this.userList = res.data.list;
        // 每一项加序号
        let serial = 1
        this.userList.forEach(item => {
            item.serial = serial
            serial++
        })
        this.total = res.data.total;
      });
    },
    // 搜索
    searchInputList() {
        this.getDataList()
    },
    // 重置数据
    setFormData() {
      this.formData = {
        id: 0, //id>0为修改，=0为添加
        region_id: "", //行政区域ID
        username: "", //用户名(6-32位)
        password: "", //密码(6-32位)
        role_id: "", //角色|ID
        name: "", //姓名
        sex: 1, //性别 1-男 2-女 3-保密
        phone: "", //电话
        head_img: "", // 头像
        age: "", //年龄
        is_stop: "1", //是否禁用 1-否 2-是
        user_area: "xf",
      };
      this.fileLlist = [];
    },
    // 编辑
    edit(row) {
      this.isPwdShow = false;
      this.dialogFormVisible = true;
      this.title = "编辑";
      let data = {
        id: row.id,
        region_id: row.region_id,
        username: row.username,
        password: row.password,
        role_id: row.role_id,
        name: row.name,
        sex: row.sex + "",
        phone: row.phone,
        head_img: row.head_img,
        age: row.age,
        is_stop: row.is_stop,
      };
      this.formData = data;
      this.fileLlist = [{ url: this.upDataUrl + row.head_img }];
      setTimeout(() => {
        let img = document.getElementsByClassName("img")[0];
        img.children[1].style.display = "none";
      }, 100);
    },
    // 添加
    add() {
      this.isPwdShow = true;
      this.dialogFormVisible = true;
      this.title = "添加";
    },
    isStop(row) {
        this.$api.post("/unit/XfUser/Save", {
          id: row.id,
          is_stop: row.is_stop,
        }).then(res => {
            if (res.code === 200) {
                this.$message({
                    type: "success",
                    message: res.msg,
                });
            } else {
                this.$message({
                    type: "error",
                    message: res.msg,
                });
            }
        })
    },
    closeForm() {
      this.setFormData();
      let img = document.getElementsByClassName("img")[0];
      img.children[1].style.display = "block";
    },
    // 取消
    cancel() {
      this.dialogFormVisible = false;
      this.setFormData();
    },
    // 确定
    submitForm() {
      this.$refs.childForm.validate((valid) => {
        if (valid) {
          let data = this.formData;
          data.sex = parseInt(data.sex);
          data.phone = parseInt(data.phone);
          data.age = parseInt(data.age);
          this.$api.post("/unit/XfUser/Save", data).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg,
              });
              this.getDataList();
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
          this.dialogFormVisible = false;
          this.setFormData();
        } else {
          ElMessage.error("请填写完整");
          return false;
        }
      });
    },
    // 图片上传
    headImgUpSuccess(e) {
      this.formData.head_img = e.data.result;
    },
    // 获取角色列表
    getRoleList() {
      this.$api.get("/unit/XfRole/lists").then((res) => {
        // 去掉网格员
        res.data.forEach((item, index) => {
          if (item.role_name === "网格员") {
            res.data.splice(index, 1);
          }
        });
        this.roleList = res.data;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.searchBox {
    display: flex;
    span {
        width: 50px;
        line-height: 40px;
        text-align: center;
    }
    .search {
        width: 30%;
    }
}
.searchMain {
    height: 80px;
}
</style>
